from def_models import Base, Cookie,User,Inventory,Machine,Drug,engine,DBSession
from sqlalchemy import Column, Integer,String,Boolean, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import time

def find_passwd(tel):
    session=DBSession()
    passwd=session.query(User).filter(User.tel==tel).all()
    num=len(passwd)
    if len(passwd)==0:
        return("无记录")
    else:
        return(passwd)

def sql_init():
    try:
        Base.metadata.create_all(engine)
        session=DBSession()
        new_user = User(tel=11111,passwd="wodesgijie")
        new_machine = Machine(mid=11111,bind=11111,level=1,now="stop")
        new_inventory = Inventory(medicine=11111,line=1,number=11,enable=1)
        new_drug = Drug(drug_id=11111,drug_level=1,drug_enable=1)
        session.add(new_user)
        session.add(new_inventory)
        session.add(new_drug)
        session.add(new_machine)
        session.commit()
        session.query(User).filter(User.tel == 11111).delete()
        session.query(Machine).filter(Machine.mid == 11111).delete()
        session.query(Inventory).filter(Inventory.medicine == 11111).delete()
        session.query(Drug).filter(Drug.drug_id == 11111).delete()
        session.commit()
        session.close()
        print("数据库初始化成功")
    except:
        print("数据库初始化失败")

def get_druglist(session):
    all = []
    for i in session.query(Drug).all():
        one = []
        one.append(i.drug_id)
        one.append(i.drug_name)
        one.append(i.drug_level)
        one.append(i.drug_sell)
        one.append(i.drug_enable)
        all.append(one)
    return all

def insert_drug(session,drug):
    try:
        if drug["enable"] == "on":
            drug["enable"] = 1
        else:
            drug["enable"] = 0
        session.add(Drug(drug_id=drug["drug_id"],drug_name=drug["drug_name"],drug_level=drug["drug_level"],drug_sell=drug["drug_sell"],drug_enable=drug["enable"]))
        session.commit()
        print("OK")
        return 1
    except:
        print("NO")
        return 0


def insert_cookie(session,cookie,ip,telephone):
    #print(session.query(Cookie).filter(Cookie.cookie == cookie).time)
    cookie1=Cookie(cookie=cookie,ip=ip,tel=telephone,time=int(time.time()))
    session.add(cookie1)
    session.commit()
    return 1

def check_cookie(session,cookie):
    cookie1=session.query(Cookie).filter(Cookie.cookie == cookie).first()
    if cookie1==None:
        return 0
    else:
        if time.time()-cookie1.time >= 3600:
            return 0
        else:
            return cookie1.tel



if __name__ == "__main__":
    sql_init()
    tel=input("请输入一个手机号")
    print("find：" + find_passwd(tel))
    session=DBSession()
    for i in get_druglist(session=session):
        print(i)
    session.close()
    session=DBSession()
    print(session.query(Cookie).filter(Cookie.cookie == "11111").first())
    session.close()